process.env.NODE_ENV = 'development';
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const os = require('os');

const configuration = require('../webpack.config');

const compiler = webpack(configuration);

const c = configuration.devServer;

let firstOpen = true;
// const firstPort = c.port;

let devServer = new WebpackDevServer(compiler, {
  ...c,
  // open: firstOpen,
});

function getIp() {
  const result = [];

  try {
    const emptyReg = /[\s\r\n]+/g;

    let network = JSON.parse(JSON.stringify(os.networkInterfaces()).replace(emptyReg, ''));

    Object.keys(network).forEach((key) => {
      const ipArr = network[key];
      if (Array.isArray(ipArr)) {
        let rightItem = ipArr.find(
          (item) =>
            item.family && item.family.toLowerCase() === 'ipv4' && item.address !== '127.0.0.1' && !item.internal,
        );
        if (rightItem && rightItem.address) {
          result.push(rightItem.address);
        }
      }
    });
  } catch (e) {
  } finally {
    result.unshift('localhost');
  }
  return result;
}

devServer.listen(c.port, c.host, () => {
  if (firstOpen) {
    getIp().forEach((ip) => {
      const name = ip === 'localhost' ? '   Local Address : ' : 'Intranet Address : ';
      const schema = 'http';
      console.log(name, `${schema}://${ip}:${c.port}`);
    });
  }
  firstOpen = false;
});
